﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.ObjectModel;
using System.Management;
using System.Management.Automation;
using Microsoft.Online.Administration;
using System.Configuration;
 
/// <summary>
/// Summary description for AzureAD
/// </summary>
public class AzureAD : Connector
{

    //no Sessions, no runtimes
    PowerShell Instance;
    string ConnectCommand;
    string SearchCommand;
    string ChangePassCommand;
    public AzureAD()
    {
        GetSettingsFromConfig();
        Instance=GetConnect();

        if (ConfigurationManager.AppSettings["AzurePSWConnect"] != null)
        {
            ConnectCommand = ConfigurationManager.AppSettings["AzurePSWConnect"];
        }
        else
        {
            ConnectCommand = "$user = '{0}'; $password = ConvertTo-SecureString '{1}' -AsPlainText -Force; $LiveCred = New-Object System.Management.Automation.PsCredential($user,$password); Import-Module MSOnline; Connect-MsolService -Credential $LiveCred;";
        }
        if (ConfigurationManager.AppSettings["AzurePSWFindUser"] != null)
        {
            SearchCommand = ConfigurationManager.AppSettings["AzurePSWFindUser"];
        }
        else
        {
            SearchCommand = " Get-MsolUser -SearchString ";
        }
        if (ConfigurationManager.AppSettings["AzurePSWChangePassword"] != null)
        {
            ChangePassCommand = ConfigurationManager.AppSettings["AzurePSWChangePassword"];
        }
        else
        {
            ChangePassCommand = "Set-MsolUserPassword -ForceChangePassword $false -userPrincipalName {0} -NewPassword {1}";
        }
    }
    public override dynamic GetConnect()
    {
        PowerShell PowerShellInstance = PowerShell.Create(); 
        //i feel sick
        //http://stackoverflow.com/questions/16018732/msonline-cant-be-imported-on-powershell-connect-msolservice-error
        PowerShellInstance.AddScript(
            String.Format(ConnectCommand, Login, Password)
        ); 
        PowerShellInstance.Invoke();
        return PowerShellInstance;
    }
    public override List<dynamic> GetUsers()
    {

        return null;
    }
    public override void ChangeUserProperty(dynamic User, CatalogProperty[] Props)
    {
      
    }
    public override List<dynamic> FindUsers(CatalogProperty[] Props, bool OneEnough)
    {
        return null;
    }
    public override dynamic FindUser(CatalogProperty[] Props, bool OneEnough)
    {
        string Command = "";
        string SearchString="";
        string CommonProperties="";
        foreach (CatalogProperty prop in Props)
        {
            if (prop.Property == "Name" || prop.Property == "FirstName" || prop.Property == "LastName")
            {
                SearchString += prop.Value + " ";
            }else
            {
                CommonProperties += "$_."+prop.Property+" -eq \""+prop.Value+"\" -and ";
            }
            //Command += String.Format(" {0} '{1}' ", prop.Property, prop.Value);
        }
        SearchString=SearchString.Trim();
        if (CommonProperties.Length > 0)
        {
            CommonProperties = CommonProperties.Substring(0, CommonProperties.Length - 6);
            Command = SearchCommand + "\""+SearchString+"\" | Where {"+ CommonProperties+" }" ;
        }else
        {
            CommonProperties = CommonProperties.Substring(0, CommonProperties.Length - 3);
            Command = String.Format(SearchCommand +"\"{0}\"", SearchString);
        }
        Instance.AddScript(Command);
        var result = Instance.Invoke();

        return result[0].BaseObject;
    }
    public override string CreateUser(CatalogProperty[] Props)
    {
        return "NotImplemented";
    }
    public override bool ChangePassword(dynamic User, string Password)
    {
       User USR = User;

       string Command = String.Format(ChangePassCommand, USR.UserPrincipalName, Password) ;
        Instance.AddScript(Command);
        var res = Instance.Invoke();

        if(Instance.HadErrors==true)
        { return false; }
        return true;
    }
}